package com.huifaapp.mall.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.huifaapp.mall.R;
import com.huifaapp.mall.adapter.GoodstoboAdapter;
import com.huifaapp.mall.adapter.PendingCommAdapter;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.GoodstoboBean;
import com.huifaapp.mall.bean.event.OrderStatusEventMessage;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class GoodstoboActivity extends AppCompatActivity {


    //  private List<GoodsReceivedBean.DataBean> goods;
    private TextView recename,recephone,receaddress,runprice,redbag,sjprice,sendaddress;
    private TextView startpay,creatpay,ddnum,zfjynum;
    private Button bt_goods_receive;
    private List<GoodstoboBean.DataBean.OrderItemBean> orderdata;
    private GoodstoboBean.DataBean goods;
    private GoodstoboBean goodstoboBean;
    private GoodstoboAdapter goodstoboAdapter;
    private PendingCommAdapter pendingCommAdapter;
    private String orderNo;
    private Button bt_kefu;
    LinearLayout listLayout;
    private GoodstoboAdapter.MyViewHolder viewHolder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goodstobo);
        initView();
        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = getIntent();
        orderNo = intent.getStringExtra("orderNo");
        Log.e("收货详情url--------","http://develop.jhjvip.cn:8080/mall/mobile/orders/notrecieveddetail"+"?token="+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+AUniqueIdentifier.getDeviceId(GoodstoboActivity.this)+"&orderNo="+orderNo);

        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"orders/notrecieveddetail")
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(this))
                .addParams("orderNo",orderNo)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                try {
                    Gson gson = new Gson();
                    goodstoboBean = gson.fromJson(response,GoodstoboBean.class);
                    goods = goodstoboBean.getData();
                    orderdata = goods.getOrderItem();
                    createShopItem(listLayout, orderdata);
                    //  sendaddress.setText(goodstoboBean.getExpressDesc());
                    recename.setText(goodstoboBean.getData().getReceiverName());
                    recephone.setText(goodstoboBean.getData().getReceiverPhone()+"");
                    receaddress.setText(goodstoboBean.getData().getReceiverAddress());
                    runprice.setText(goodstoboBean.getData().getExpressfee()+"");
                    redbag.setText(goodstoboBean.getData().getCouponAmount()+"");
                    sjprice.setText(goodstoboBean.getData().getActualpay()+"");
                    zfjynum.setText(goodstoboBean.getData().getPayno()+"");
                    ddnum.setText(goodstoboBean.getData().getOrderNo()+"");
                    // startpay.setText(goodstoboBean.getData().getPaytime()+"");
                    creatpay.setText(goodstoboBean.getData().getCreatetime()+"");
                    //   sendtime.setText(goodstoboBean.getSysTime()+"");
                }catch (Exception e){
                    ToastUtils.showShort("获取失败");
                }

            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Intent intent = getIntent();
        orderNo = intent.getStringExtra("orderNo");
        Log.e("收货详情url--------","http://develop.jhjvip.cn:8080/mall/mobile/orders/notrecieveddetail"+"?token="+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+AUniqueIdentifier.getDeviceId(GoodstoboActivity.this)+"&orderNo="+orderNo);

        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"orders/notrecieveddetail")
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(this))
                .addParams("orderNo",orderNo)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                try {
                    Gson gson = new Gson();
                    goodstoboBean = gson.fromJson(response,GoodstoboBean.class);
                    goods = goodstoboBean.getData();
                    orderdata = goods.getOrderItem();
                    createShopItem(listLayout, orderdata);
                    //  sendaddress.setText(goodstoboBean.getExpressDesc());
                    recename.setText(goodstoboBean.getData().getReceiverName());
                    recephone.setText(goodstoboBean.getData().getReceiverPhone()+"");
                    receaddress.setText(goodstoboBean.getData().getReceiverAddress());
                    runprice.setText(goodstoboBean.getData().getExpressfee()+"");
                    redbag.setText(goodstoboBean.getData().getCouponAmount()+"");
                    sjprice.setText(goodstoboBean.getData().getActualpay()+"");
                    zfjynum.setText(goodstoboBean.getData().getPayno()+"");
                    ddnum.setText(goodstoboBean.getData().getOrderNo()+"");
                    // startpay.setText(goodstoboBean.getData().getPaytime()+"");
                    creatpay.setText(goodstoboBean.getData().getCreatetime()+"");
                    //   sendtime.setText(goodstoboBean.getSysTime()+"");
                }catch (Exception e){
                    ToastUtils.showShort("获取失败");
                }

            }
        });
    }

    private void initView() {
        listLayout = (LinearLayout) findViewById(R.id.listLayout);

        bt_kefu = (Button) findViewById(R.id.goodstobo_lianxikefu);
        recename = (TextView) findViewById(R.id.goods_shname);
        recephone = (TextView) findViewById(R.id.goods_shphone);
        receaddress = (TextView) findViewById(R.id.goods_shaddress);
        runprice = (TextView) findViewById(R.id.goods_runprice);
        redbag = (TextView) findViewById(R.id.goods_bagprice);
        sjprice = (TextView) findViewById(R.id.goods_sjprice);
        //startpay = (TextView) findViewById(R.id.goods_fktime);
        creatpay = (TextView) findViewById(R.id.goods_creattime);
        ddnum = (TextView) findViewById(R.id.goods_ddnum);
        zfjynum = (TextView) findViewById(R.id.goods_zfjynum);
        //sendtime = (TextView) findViewById(R.id.goods_sendtime);
      //  sendaddress = (TextView) findViewById(R.id.goods_sendaddress);
        bt_goods_receive = (Button) findViewById(R.id.goods_receive);
        Intent intent = getIntent();
        orderNo = intent.getStringExtra("orderNo");
        Log.e("收货详情url--------","http://develop.jhjvip.cn:8080/mall/mobile/orders/notrecieveddetail"+"?token="+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+AUniqueIdentifier.getDeviceId(GoodstoboActivity.this)+"&orderNo="+orderNo);

        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"orders/notrecieveddetail")
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(this))
                .addParams("orderNo",orderNo)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                try {
                    Gson gson = new Gson();
                    goodstoboBean = gson.fromJson(response,GoodstoboBean.class);
                    goods = goodstoboBean.getData();
                    orderdata = goods.getOrderItem();
                    createShopItem(listLayout, orderdata);
                    //  sendaddress.setText(goodstoboBean.getExpressDesc());
                    recename.setText(goodstoboBean.getData().getReceiverName());
                    recephone.setText(goodstoboBean.getData().getReceiverPhone()+"");
                    receaddress.setText(goodstoboBean.getData().getReceiverAddress());
                    runprice.setText(goodstoboBean.getData().getExpressfee()+"");
                    redbag.setText(goodstoboBean.getData().getCouponAmount()+"");
                    sjprice.setText(goodstoboBean.getData().getActualpay()+"");
                    zfjynum.setText(goodstoboBean.getData().getPayno()+"");
                    ddnum.setText(goodstoboBean.getData().getOrderNo()+"");
                   // startpay.setText(goodstoboBean.getData().getPaytime()+"");
                    creatpay.setText(goodstoboBean.getData().getCreatetime()+"");
                    //   sendtime.setText(goodstoboBean.getSysTime()+"");
                }catch (Exception e){
                    ToastUtils.showShort("获取失败");
                }

            }
        });

    }

    private void createShopItem(ViewGroup viewGroup, List<GoodstoboBean.DataBean.OrderItemBean> lists){
        if (lists == null) {
            return;
        }
        viewGroup.removeAllViews();
        for (int i = 0; i < lists.size(); i++) {

            final GoodstoboBean.DataBean .OrderItemBean orderItemBean = orderdata.get(i);
            Log.e("售后orderno",goods.getOrderNo());
            Log.e("售后sku",orderItemBean.getSkuId());

            View view =  LayoutInflater.from(this).inflate(R.layout.goodstobo_item,null);
            viewHolder = new GoodstoboAdapter.MyViewHolder(view);
            final String dealstate = orderItemBean.getDealState();


            Log.e("待收货","dealstate======"+dealstate);

            Log.e("shouhuoxiangqing",dealstate);
            if(orderItemBean.getState().equals("5")){
                viewHolder.bt_ckwl.setVisibility(View.GONE);
                viewHolder.goodstobo_ckwl_pingjia.setVisibility(View.VISIBLE);
            }else {
                if (dealstate.equals("001")) {
                    viewHolder.bt_tmoney.setText("退款中");
                } else if (dealstate.equals("002")) {
                    viewHolder.bt_tmoney.setText("换货关闭/退货关闭");
                } else if (dealstate.equals("003")) {
                    viewHolder.bt_tmoney.setText("待处理");
                } else if (dealstate.equals("004")) {
                    viewHolder.bt_tmoney.setText("售后拒绝");
                } else if (dealstate.equals("005")) {
                    viewHolder.bt_tmoney.setText("同意换货填写物流");
                } else if (dealstate.equals("006")) {
                    viewHolder.bt_tmoney.setText("退款成功");
                }
            }
            viewHolder.bt_tmoney.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.e("dealstate",dealstate );
                    if (dealstate.equals("0")||dealstate.equals("007")){
                        Intent intent = new Intent(GoodstoboActivity.this,AfterSaleStateActivity.class);
                        intent.putExtra("orderNo",goods.getOrderNo());
                        intent.putExtra("skuId",orderItemBean.getSkuId()+"");
                        intent.putExtra("state",orderItemBean.getState()+"");
                        Log.e("goodstobo",goods.getOrderNo());
                        Log.e("goodsskuid",orderItemBean.getSkuId()+"");
                        //  intent.putExtra("goodsid",orderItemBean.getGoodsId()+"");
                        startActivity(intent);}

//                    }else if (dealstate.equals("003")){
//                        Intent intent = new Intent(GoodstoboActivity.this,AfterStatusActivity.class);
//                        intent.putExtra("aftersaleId",orderItemBean.getAftersaleId()+"");
//                        Log.e("daishouhuoxq",orderItemBean.getAftersaleId()+"");
//                        startActivity(intent);
//                    }
                    else {
//                        Intent intent = new Intent(GoodstoboActivity.this,AfterStatusActivity.class);
//                        intent.putExtra("aftersaleId",orderItemBean.getAftersaleId()+"");
//                        Log.e("daishouhuoxq",orderItemBean.getAftersaleId()+"");
//                        startActivity(intent);
                    }

                }
            });
            viewHolder.bt_ckwl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(GoodstoboActivity.this, com.huifaapp.mall.activity.Homefragment.WebActivity.class);
                    intent.putExtra("url",ApiManager.WU_LIU+"?appId="+AUniqueIdentifier.getDeviceId(GoodstoboActivity.this)+"&token="+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&orderNo="+orderItemBean.getOrderNo()+"&skuId="+orderItemBean.getSkuId());
//                    intent.putExtra("appId", AUniqueIdentifier.getDeviceId(GoodstoboActivity.this));
//                    intent.putExtra("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
//                    intent.putExtra("orderNo",orderItemBean.getOrderNo());
//                    intent.putExtra("skuId",orderItemBean.getSkuId());
                    Log.e("查看物流url-------",ApiManager.WU_LIU+"?appId="+AUniqueIdentifier.getDeviceId(GoodstoboActivity.this)+"&token="+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&orderNo="+orderItemBean.getOrderNo()+"&skuId="+orderItemBean.getSkuId());
                    startActivity(intent);
                }
            });
            viewHolder.goodstobo_ckwl_pingjia.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(GoodstoboActivity.this,AssessActivity.class);
                    intent.putExtra("skuid",orderItemBean.getSkuId()+"");
                    intent.putExtra("orderId",orderItemBean.getOrderNo());
                    startActivity(intent);
                }
            });
            viewHolder.setData(this, lists.get(i));
            viewGroup.addView(view);
        }
    }


    private void initData() {

        bt_kefu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GoodstoboActivity.this, com.huifaapp.mall.activity.Homefragment.WebActivity.class);
                intent.putExtra("url",ApiManager.KEFU);
                startActivity(intent);
            }
        });

        bt_goods_receive.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                orderdata = goods.getOrderItem();
                // Intent intent = getIntent();
//                String orderno = intent.getStringExtra("orderNo")

                final String orderno = goods.getOrderNo();
                goodstoboAdapter = new GoodstoboAdapter(GoodstoboActivity.this, goods, orderdata);
                // pendingCommAdapter = new PendingCommAdapter(GoodstoboActivity.this,goods)


                AlertDialog alertDialog = new AlertDialog.Builder(GoodstoboActivity.this).setTitle("提示").setMessage("是否需要确认收货？")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {


                            }
                        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {


                                OkHttpUtils.post().url(ApiManager.BASE_NIUPAI_URL+"orders/confirmReceive")
                                        .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                                        .addParams("appId", AUniqueIdentifier.getDeviceId(GoodstoboActivity.this))
                                        .addParams("orderNo", orderno)
                                        .build()
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onError(Request request, Exception e) {
                                                ToastUtils.showShort("确认收货失败");
                                            }

                                            @Override
                                            public void onResponse(String response) {
                                                // Log.e("HB", response);
                                                try {
                                                    JSONObject jsonObject = new JSONObject(response);
                                                    String code = jsonObject.getString("code");
                                                    String msg = jsonObject.getString("msg");
                                                    if (code.equals("10000")) {
                                                        ToastUtils.showShort(msg);

                                                        EventBus.getDefault().post(new OrderStatusEventMessage(
                                                                OrderStatusEventMessage.TYPE_RECEIVED,
                                                                orderNo));

                                                        viewHolder.bt_ckwl.setVisibility(View.GONE);
                                                        viewHolder.goodstobo_ckwl_pingjia.setVisibility(View.VISIBLE);
                                                    } else {
                                                        ToastUtils.showShort(msg);
                                                    }
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }


                                            }
                                        });

                            }
                        }).create();
                alertDialog.show();
            }
        });


    }

}
